package com.simtop.service.impl;

import com.alibaba.excel.metadata.BaseRowModel;
import com.simtop.domain.user.SysUser;
import com.simtop.mapper.RoleMapper;
import com.simtop.mapper.SysUserMapper;
import com.simtop.mapper.UserRoleMapper;
import com.simtop.security.SecurityUtils;
import com.simtop.service.SysUserService;
import com.simtop.utils.ResultBean;
import com.simtop.utils.excel.ExcelUtils;
import com.simtop.utils.ifnull.StringUtils;
import com.simtop.utils.token.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @ClassName SysUserServiceImpl
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-08-17 18:07
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;


    /**
     * token工具
     */
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 导入导出工具类
     */
    @Autowired
    private ExcelUtils excelUtils;

    private Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     */
    @Override
    public SysUser getUserByUserName(String userName) {
        return sysUserMapper.getUserByUserName(userName);
    }

    /**
     * 注册/添加系统用户
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertSysUser(SysUser sysUser) {
             sysUserMapper.insertSysUser(sysUser);
             /**
              * 获取添加用户后返回的主键id
              */
             Long userId = sysUser.getUserId();
             /**
              * 执行添加角色的方法
              */
             return userRoleMapper.insertUserRole(userId,sysUser.getRoleIds());
    }

    /**
     * 判断用户名是否重复
     * @param userName
     * @return
     */
    @Override
    public SysUser verifyUserName(String userName) {
        return sysUserMapper.verifyUserName(userName);
    }

    /**
     * 判断电话是否重复
     * @param phone
     * @return
     */
    @Override
    public SysUser verifyPhone(String phone) {
        return sysUserMapper.verifyPhone(phone);
    }

    /**
     * 判断邮箱是否重复
     * @param email
     * @return
     */
    @Override
    public SysUser verifyEmail(String email) {
        return sysUserMapper.verifyEmail(email);
    }

    /**
     * 修改密码
     * @param userName 用户名
     * @param password 新密码
     * @return
     */
    @Override
    public boolean updatePassword(String userName, String password) {
        return sysUserMapper.updatePassword(userName,password);
    }

    /**
     * 删除 / 停用用户
     * @param userIds    用户id
     * @param delStatus   用户状态
     * @return
     */
    @Override
    public boolean changeUserStatus(Long[] userIds, int delStatus) {
        return sysUserMapper.changeUserStatus(userIds,delStatus);
    }

    /**
     * 修改用户信息
     * @param sysUser  系统用户信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSysUser(SysUser sysUser) {
        /**
         * 判断是否修改角色
         */
        if(StringUtils.isNull(sysUser.getRoleIds()) || sysUser.getRoleIds().length == 0){
            return sysUserMapper.updateSysUser(sysUser);
        }else{
            Long userId = sysUser.getUserId();
            /**
             * 角色信息修改,删除原有用户角色关联再添加
             */
            userRoleMapper.deleteUserRole(userId);
            userRoleMapper.insertUserRole(userId,sysUser.getRoleIds());
            return sysUserMapper.updateSysUser(sysUser);
        }
    }


    /**
     * 导入用户信息
     * @param file   导入的用户信息
     * @param sysUser   用户所属班级，专业，院系，角色等
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean importSysUser(MultipartFile file, SysUser sysUser) {
        /**
         * 解析用户信
         */
        List<BaseRowModel> sysUserList = excelUtils.upload(file,SysUser.class);
        //记录失败信息
        StringBuilder failureMsg = new StringBuilder();
        //记录成功信息
        StringBuilder successMsg = new StringBuilder();
        //记录成功条数
        int failCount = 0;
        //记录失败条数
        int successCount = 0;
        /**
         * 设置统一密码
         */
        String password = SecurityUtils.encryptPassword("123456");
        if(StringUtils.isNull(sysUserList) || sysUserList.size() == 0){
            return ResultBean.error("请按照模板添加用户信息,再上传文件");
        }
        /**
         * 循环判断并添加用户
         */
        for(Object sysUser1 : sysUserList){
            SysUser user = (SysUser) sysUser1;
            /**
             * 判断某些项没有，则不导入
             */
            if(StringUtils.isNull(user.getUserName()) || StringUtils.isNull(user.getRealName()) || StringUtils.isNull(user.getPhone()) || StringUtils.isNull(user.getEmail())){
                continue;
            }
            try{
                /**
                 * 判断用户名是否存在
                 */
                SysUser sysUser2 = sysUserMapper.verifyUserName(user.getUserName());
                /**
                 * 判断手机号是否存在
                 */
                SysUser sysUser3 = sysUserMapper.verifyPhone(user.getPhone());
                /**
                 * 判断邮箱账号是否存在
                 */
                SysUser sysUser4 = sysUserMapper.verifyEmail(user.getEmail());
                if(StringUtils.isNull(sysUser2) && StringUtils.isNull(sysUser3) && StringUtils.isNull(sysUser4) && !StringUtils.isNull(user.getUserName())
                        && !StringUtils.isNull(user.getRealName()) && !StringUtils.isNull(user.getPhone())){
                    /**
                     * 设置密码，以及所属班级,专业,院系
                     */
                     user.setPassword(password);
                    /**
                     * 角色
                     */
                    user.setRoleIds(sysUser.getRoleIds());
                    /**
                     * 调用插入方法
                     */
                    insertSysUser(user);

                    /**
                     * 导入成功记录
                     */
                    successCount ++;
                    successMsg.append("<br/>" + successCount + "、账号 " + user.getUserName() + " : "+ user.getRealName() +  " 导入成功");
                } else {
                    failCount++;
                    if(!StringUtils.isNull(sysUser2)){
                        failureMsg.append("<br/>" + failCount + "、账号 " + user.getUserName() + " 已存在");
                    }
                    if(!StringUtils.isNull(sysUser3)){
                        failureMsg.append("<br/>" + failCount + "、账号 " + user.getUserName() + "的手机号" + user.getPhone()+ "已存在");
                    }
                    if(!StringUtils.isNull(sysUser4)){
                        failureMsg.append("<br/>" + failCount + "、账号 " + user.getUserName() + "的邮箱号" + user.getEmail()+ "已存在");
                    }
                }
            }catch (Exception e){
                failCount++;
                String msg = "<br/>" + failCount + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg);
                logger.error(msg, e);
            }
        }
        if (failCount > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failCount + " 条数据格式不正确，错误如下：");
            return ResultBean.error(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successCount + " 条，数据如下：");
            return ResultBean.success(successMsg.toString());
        }
    }

    /**
     * 重置密码
     * @param sysUser
     * @return
     */
    @Override
    public boolean resetPassword(SysUser sysUser) {
        return sysUserMapper.updateSysUser(sysUser);
    }
}
